use actix_web:: {web, HttpResponse, Responder};
use diesel::prelude::*;
use crate::db::models::{NewTask, Task};
use crate::db::schema::tasks;

#[derive(serde::Deserialize)]
pub struct CreateTaskRequest {
    title: String,
    description: String,
    due_date: Option<chrono::NaiveDateTime>,
}

pub async fn create_task (
    pool: web::Data<db::DbPool>,
    task_request: web::Json<CreateTaskRequest>,
) -> impl Responder {
    // HACK:
    let conn = pool.get().expect("asd");

    let new_task = NewTask {
        title: &task_request.title,
        description: &task_request.description,
        due_date: task_request.due_date,
    };

    let task = web::block(move || {
        diesel::insert_into(task::table)
            .value(&new_task)
            .get_result::<Task>(&conn)
    })
    .await
        .map_err(|e| {
            eprintln!("{}", e);
            HttpResponse::InternalServerError().finish()
        })?;
    
    Ok(HttpResponse::Created().json(task))
}
